#include <assert.h>
#include "autoorderbreak.h"

AutoOrderBreak::AutoOrderBreak()
: AutoOrderBase()
, m_atr(1.2)
, m_magic(10001)
{
    m_orderManager = OrderManager::inst();
}

void AutoOrderBreak::newTick(double price, time_t time)
{
    int buyorderNum = 0, sellorderNum = 0;
    assert (m_index >= 0 && m_index < m_bars->getSize());
    m_time = time;
    m_price = price;
    BUYSELLSIGNAL buysellSignal = getBuySellSignal();

    std::vector<NormalOrder*> vecOrder = m_orderManager->getNormOrders();
    for (int i = 0; i < vecOrder.size(); ++i) {
        if (vecOrder[i]->getOrderType() == OrderBase::ORDERBUY) {
            buyorderNum++;
        }
        else if (vecOrder[i]->getOrderType() == OrderBase::ORDERSELL) {
            sellorderNum++;
        }
    }

    if (buysellSignal == BUYSIGNAL && buyorderNum == 0) {
        buy();
    }
    else if (buysellSignal == SELLSIGNAL && sellorderNum == 0) {
        sell();
    }
}

AutoOrderBreak::BUYSELLSIGNAL AutoOrderBreak::getBuySellSignal()
{
    double ATR = 0;
    for (int i = 1; i <= 12; ++i) {
        ATR = ATR + high(i) - low(i);
    }
    ATR /= 12;
    float lastPrice = close(1);
    if (m_price - lastPrice > ATR * m_atr)
        return BUYSIGNAL;
    else if (lastPrice - m_price > ATR * m_atr)
        return SELLSIGNAL;
    return NOSIGNAL;
}

void AutoOrderBreak::buy()
{
    NormalOrder *order = createBuyOrder(m_time, m_bars->getSymbol(), m_price, 0.1, m_price - 0.0100, 0, m_magic);
    if (order) {
        order->setTrailStop(true, 200);
    }
}

void AutoOrderBreak::sell()
{
    NormalOrder *order = createSellOrder(m_time, m_bars->getSymbol(), m_price, 0.1, m_price + 0.0100, 0, m_magic);
    if (order) {
        order->setTrailStop(true, 200);
    }
}

void AutoOrderBreak::changeStoploss()
{
}